﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleScale.Models;
using Janus.Windows.GridEX;

namespace VehicleScale.Forms.Vehicles
{
    public partial class FrmVehicleScaleSplit : TemplateForm
    {

        #region Properties
        private IList<VehicleScaleSplitModel> _splitCollection;
        public IList<VehicleScaleSplitModel> SplitCollection
        {
            get
            {
                return _splitCollection;
            }
            set
            {
                if (_splitCollection != value)
                {
                    _splitCollection = value;
                }
            }
        }

        public decimal TotalWeight
        {
            get;
            set;
        }

        private bool _isEdit = false;
        #endregion

        #region Ctors
        public FrmVehicleScaleSplit(IList<VehicleScaleSplitModel> vehibleScaleSplits)
        {
            InitializeComponent();

            this.btnSave.Click += new EventHandler(delegate { ClickButtonSave(); });
            this.btnClose.Click += new EventHandler(delegate
            {
                if (_isEdit)
                {
                    DialogResult result = Library.Tools.MsgBox.Show("Số lần chia tổng trọng đã có thay đổi! Bạn có muốn lưu hay không?", "Thông báo", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                    switch (result)
                    {
                        case DialogResult.No:
                            this.Close();
                            break;
                        case DialogResult.Yes:
                            this.ClickButtonSave();
                            break;
                    }
                }
                else
                {
                    this.Close();
                }
            });
            this.btnSplit.Click += new EventHandler(delegate { ClickButtonSplit(); });

            this.cboCategoryID.ValueChanged += new EventHandler(delegate { FilterProduct(); });

            this.gridEX1.ColumnButtonClick += new Janus.Windows.GridEX.ColumnActionEventHandler(gridEX1_ColumnButtonClick);

            if (SplitCollection == null) SplitCollection = new List<VehicleScaleSplitModel>();
            foreach (var item in vehibleScaleSplits)
            {
                SplitCollection.Add(item.Clone<VehicleScaleSplitModel>());
            }
            this.gridEX1.DataBindings.Add("DataSource", this, "SplitCollection");
        }

        void gridEX1_ColumnButtonClick(object sender, ColumnActionEventArgs e)
        {
            if (e.Column.Key == "ButtonDelete")
            {
                VehicleScaleSplitModel model = this.gridEX1.CurrentRow.DataRow as VehicleScaleSplitModel;
                
                if (model == null) return;
                if(Common.UserLogin.GroupPermissionID != 1 &&
                    new FrmAuthorize().ShowDialog() != DialogResult.OK) return;

                this.gridEX1.CurrentRow.Delete();
                _isEdit = true;

            }
        }

        #endregion

        #region Events
        protected override void OnLoad(EventArgs e)
        {
            LoadCategoriesToCombo();
            LoadProductsToCombo();

            this.numTotalWeight.Value = TotalWeight;

            base.OnLoad(e);
        }
        #endregion

        #region Methods

        /// <summary>
        /// Save Method
        /// </summary>
        void ClickButtonSave()
        {
            decimal sumWeight = _splitCollection.Sum(v => v.Weight);
            decimal totalWeight = Convert.ToDecimal(this.numTotalWeight.Value);
            decimal currentWeight = Convert.ToDecimal(this.numWeight.Value);
            if (sumWeight == totalWeight || sumWeight == 0)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                Library.Tools.MsgBox.Show("Tổng trọng lượng chia không trùng khớp với tổng trọng lượng cân thực tế.", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Split Method
        /// </summary>
        void ClickButtonSplit()
        {
            decimal sumWeight = _splitCollection.Sum(v => v.Weight);
            decimal totalWeight = Convert.ToDecimal(this.numTotalWeight.Value);
            decimal currentWeight = Convert.ToDecimal(this.numWeight.Value);
            if (sumWeight + currentWeight > totalWeight)
            {
                Library.Tools.MsgBox.Show("Tổng trọng lượng chia đã vượt quá tổng trọng lượng cân thực tế.", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (this.cboProductID.Value == null)
                {
                    Library.Tools.MsgBox.Show("Bạn chưa chọn hàng hóa cần chia!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    SplitCollection.Add(new VehicleScaleSplitModel() { 
                        VehicleScaleSplitID = Guid.NewGuid(),
                        Weight = currentWeight, 
                        Description = this.editBox1.Text, 
                        ProductID = this.cboProductID.Value.ToString(), 
                        Product = this.cboProductID.SelectedItem as ProductModel 
                    });
                    this.gridEX1.Refetch();
                    _isEdit = true;
                }
            }
        }

        /// <summary>
        /// Filter the products list.
        /// </summary>
        private void FilterProduct()
        {
            if (this.cboProductID.DropDownList.CurrentRow != null
                && this.cboProductID.DropDownList.CurrentRow.Cells["CategoryID"].Value != cboCategoryID.Value)
            {
                this.cboProductID.SelectedIndex = -1;
            }

            GridEXFilterCondition condition = new GridEXFilterCondition();
            condition.Column = this.cboProductID.DropDownList.RootTable.Columns["CategoryID"];
            condition.ConditionOperator = ConditionOperator.Equal;
            condition.Value1 = cboCategoryID.Value;

            this.cboProductID.DropDownList.RootTable.FilterCondition = condition;

        }

        /// <summary>
        /// Load category list to combo
        /// </summary>
        private void LoadCategoriesToCombo()
        {
            this.cboCategoryID.DataSource = Common.Categories;
            this.cboCategoryID.ValueMember = "CategoryID";
            this.cboCategoryID.DisplayMember = "CategoryName";
        }

        /// <summary>
        /// Load product list to combo
        /// </summary>
        private void LoadProductsToCombo()
        {
            this.cboProductID.DataSource = Common.Products;
            this.cboProductID.ValueMember = "ProductID";
            this.cboProductID.DisplayMember = "ProductName";
            this.cboProductID.DropDownList.Columns.Add("CategoryID", Janus.Windows.GridEX.ColumnType.Text);
        }

        #endregion

    }
}
